package cn.kow.kmall.controller;

import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.pojo.dto.AddressDTO;
import cn.kow.kmall.pojo.entity.Address;
import cn.kow.kmall.pojo.vo.AddressVO;
import cn.kow.kmall.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-05-13 15:27
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping(value = "/list")
    public KmallResult list(@RequestAttribute Long uid) {
        List<Address> addressList = addressService.list(uid);
        List<AddressVO> voList = addressList.stream().map(address ->
            {
                AddressVO addressVO = new AddressVO();
                BeanUtils.copyProperties(address, addressVO);
                return addressVO;
            }).collect(Collectors.toList());
        return KmallResult.success(voList);
    }

    @GetMapping(value = "/info")
    public KmallResult info(@RequestAttribute Long uid, @RequestParam Long id) {
        Address address = addressService.get(uid, id);
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(address, addressVO);
        return KmallResult.success(addressVO);
    }

    @PostMapping(value = "/save")
    public KmallResult update(@RequestAttribute Long uid, @RequestBody AddressDTO addressDTO) {
        Address address = addressService.addOrUpdate(uid, addressDTO);
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(address, addressVO);
        return KmallResult.success(addressVO);
    }

    @PostMapping(value = "/del")
    public KmallResult del(@RequestAttribute Long uid, @RequestBody Map<String, String> param) {
        Long id = Long.valueOf(param.get("id"));
        Address address = addressService.get(uid, id);
        if (address == null) {
            return KmallResult.fail();
        }
        addressService.delete(id);
        return KmallResult.success();
    }

}
